import datetime
import re
import json
import requests
import uuid
from bisheng.database.models.message import ChatMessage, ChatMessageDao, ChatMessageRead
from bisheng.api.jsj_api.model.metro_fault import ConfigDao
from bisheng.api.jsj_api.tool_service import MetroFaultService as ToolService
from bisheng.utils.logger import logger
from .utils.simple_minio_client import SimpleMinioClient


class PowerService:

    def __init__(self):
        pass

    def get_suggest_question(self,chat_id,workflow=False):
        flag = False
        messages = []
        # if isinstance(chat_id, str):
        #     chat_id = UUID(chat_id)
        res = ChatMessageDao.get_messages_by_chat_id_last(chat_id=chat_id, category_list=["answer","question","stream_msg"], limit=2)
        if res is None or len(res) == 0:
            print("当前chat_id未获取到对话")
            return None
        else:
            print(res)
            content = {}
            #表示工作流
            if res[0].type == 'workflow':
                flag = True
                content['content'] = self.create_content_workflow(res,workflow)
            else:
                content['content'] = self.create_content(res)
            content['role'] = 'user'
            messages.append(content)
            print(messages)

            if workflow:
                workflow_id = ConfigDao.get_config_by_key("get_suggest_question_workflow_id").value
                return_content = self.use_workflow_by_id(workflow_id,messages)
            else:
                model_id = ConfigDao.get_config_by_key("get_suggest_question_model_id").value
                return_content = self.use_model_by_id(model_id,messages)
            logger.info(f"-----return_content-----:{return_content}")
            if return_content is None or not return_content.strip() or return_content == "''":
                return None
            if flag:
                return_list = self.split_by_semicolon(return_content)
            else:
                return_list = self.extract_content_after_colon(return_content)
            logger.info(f"-----return_list-----:{return_list}")
            if len(return_list) == 0:
                return [return_content]

            return return_list

    @staticmethod
    def create_content(res):
        human_messages = []
        expert_messages = []

        for message in res:
            if message.type == 'human':
                human_messages.append(f"用户：{json.loads(message.message)['input']}")
            else:
                expert_messages.append(f"专家：{message.message}")

        # 将人类消息放在前面，专家消息放在后面
        all_messages = human_messages + expert_messages

        # 将所有消息连接成一个字符串，每条消息后面加上换行符
        content = "\n".join(all_messages) + "\n"

        return content


    def create_content_workflow(self,res,workflow):
        human_messages = []
        expert_messages = []
        workflow_content = {}
        for message in res:
            if message.category == 'question':
                logger.info(f"question:{message.message}")
                if workflow:
                    workflow_content['description'] = self.get_description_by_group_id(json.loads(message.message)['group_id'])
                    workflow_content['group_id'] = json.loads(message.message)['group_id']
                    workflow_content['user_input'] = message.message
                human_messages.append(f"用户：{message.message}")
            if message.category == 'stream_msg':
                if workflow:
                    workflow_content['ai_output'] = json.loads(message.message)['msg']
                expert_messages.append(f"AI：{json.loads(message.message)['msg']}")
                # 将人类消息放在前面，专家消息放在后面
        all_messages = human_messages + expert_messages

        # 将所有消息连接成一个字符串，每条消息后面加上换行符
        content = "\n".join(all_messages) + "\n"

        if workflow:
            return workflow_content

        return content




    @staticmethod
    def use_model_by_id(model_id, messages):
        url = ConfigDao.get_config_by_key("use_model_url")
        headers = {
            'Content-Type': 'application/json'
        }

        payload = json.dumps({
            "model": model_id,
            "messages": messages,
            "stream": False
        })
        print("payload:", payload)

        try:
            response = requests.post(url.value, headers=headers, data=payload)
            print("response:", response.text)
            ToolService.add_request_record(payload, response.text, url.value, response.status_code, "post")
            if response.status_code == 200:
                response_content = ToolService.get_content_from_response(response)
                print("response_content",response_content)
                return response_content

            else:
                print(f"调用模型助手失败，状态码：{response.status_code}")
        except Exception as e:
            print(f"发生错误：{e}")

        return ""

    @staticmethod
    def extract_content_after_colon(text):
        # 使用正则表达式匹配引导词和冒号后的内容
        pattern = r'引导词\d+[：:]\s*(.*?)(?=引导词\d+[：:]|$)'
        matches = re.findall(pattern, text, re.DOTALL)

        # 清理和存储提取的内容
        extracted_contents = [content.strip() for content in matches if content.strip()]

        return extracted_contents
    @staticmethod
    def split_by_semicolon(text):
        """
        使用英文分号切分文本。

        Args:
            text: 要切分的文本。

        Returns:
            切分后的字符串列表。
        """
        parts = re.split(r';', text)
        return [part.strip() for part in parts if part.strip()]
        # return re.split(r';', text)

    @staticmethod
    def get_chat_message_by_chat_id(chat_id):
        res = ChatMessageDao.get_messages_by_chat_id_last(chat_id=chat_id,
                                                          category_list=["answer", "question", "stream_msg"], limit=20)
        if res is None or len(res) == 0:
            print("当前chat_id未获取到对话")
            return None

        messages = []
        for message in res:
            if message.category == "question":
                messages.append(f"用户：{json.loads(message.message)['content']['message']}")
            if message.category == "stream_msg":
                messages.append(f"AI:{json.loads(message.message)['msg']}")
        reversed_messages = list(reversed(messages))  # 转换为列表
        return reversed_messages

    @staticmethod
    def use_workflow_by_id(workflow_id,message):
        ##workflow 暂时只支持message 不支持数组
        message = message[0].get('content',None) if message else None
        logger.info(f"---workflow-content---:{message}")
        url = ConfigDao.get_config_by_key("use_workflow_invoke_url").value

        payload = json.dumps({
            "workflow_id": workflow_id,
            "stream": False
        })

        headers = {
            'Content-Type': 'application/json'
        }
        response = requests.request("POST", url, headers=headers, data=payload)

        if response.status_code != 200:
            raise Exception("请求工作流失败")
        response_text = response.text
        logger.info(f"响应内容（字符串）: {response_text}")

        response_data = json.loads(response_text)

        # for line in response_text.splitlines():
        #     if line.startswith("data: "):
        #         json_str = line[6:]
        #         response_data = json.loads(json_str)

        logger.info(f"---------------------{response_data}")

        node_id = ''
        message_id = ''

        result = {}
        for event in response_data["data"]["events"]:
            if event['event'] == 'input':
                node_id = event['node_id']
                message_id = event['message_id']
            if event["event"] == "input" and event["input_schema"] and event["input_schema"]["input_type"] == "form_input":
                for item in event["input_schema"]["value"]:
                    key = item["key"]
                    if key in message:
                        result[key] = message[key]

        logger.info(f"---------11------------{result}")

        payload_new =  json.dumps({
            "workflow_id": workflow_id,
            "stream": False,  # 启用流式传输
            "input": { node_id: result },
            "message_id": message_id,
            "session_id": response_data['data']['session_id']
        })

        response = requests.request("POST", url, headers=headers, data=payload_new)

        if response.status_code != 200:
            raise Exception("请求工作流失败")

        response_text = response.text
        logger.info(f"响应内容（字符串）: {response_text}")

        response_data = json.loads(response_text)

        for event in response_data['data']['events']:
            if event['event'] == 'output_msg':
                # 提取 output_schema 中的 message
                message = event['output_schema']['message']
                print(f"Message: {message}")
                break  # 找到后退出循环

        logger.info(f"--------++++++++++++++++++-------------{response_data}")

        return message

    @staticmethod
    def get_description_by_group_id(group_id):
        alarm_records = ToolService.get_alarm_record_by_group_id(group_id)
        if alarm_records is None or len(alarm_records) == 0:
            return ""
        return alarm_records[0].description

    @staticmethod
    def get_chat_history(chat_id,page_size):
        #category_list=["answer", "question", "stream_msg"]
        res = ChatMessageDao.get_messages_by_chat_id_last(chat_id=chat_id,
                                                          category_list = None, limit=page_size)
        if res is None or len(res) == 0:
            return None
        return res[::-1]

    @staticmethod
    def get_alarm_report_by_group_id(group_id,chat_id):
        alarm_records = ToolService.get_alarm_record_by_group_id(group_id)
        if alarm_records is None or len(alarm_records) == 0:
            return ""
        alarm_end_datetime_str = None
        if chat_id:
            chat_list = ToolService.get_alarm_status_by_chat_id(chat_id)
            if len(chat_list) > 0:
                alarm_end_datetime_str = chat_list[0].update_time
            

        #告警时间
        alarm_datetime = alarm_records[0].alarm_time
        alarm_datetime_str = alarm_datetime.strftime("%Y年%m月%d日 %H时%M分%S秒")
        alarm_date = alarm_datetime.strftime("%Y-%m-%d")
        alarm_date_str = alarm_datetime.strftime("%m.%d")
        alarm_time = alarm_datetime.strftime("%H:%M")
        alarm_time_str = alarm_datetime.strftime("%H.%M")
        description = alarm_records[0].description
        placeholders = {"alarm_datetime_str":alarm_datetime_str, "alarm_date":alarm_date,
                        "alarm_time":alarm_time, "alarm_time_str":alarm_time_str,"alarm_date_str":alarm_date_str,
                        "alarm_end_datetime_str": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),}
        if alarm_end_datetime_str:
            placeholders["alarm_end_datetime_str"] = alarm_end_datetime_str

        filename = uuid.uuid4()  # 生成一个随机 UUID
        object_name = "create_alarm_report_docx/" + str(filename) + ".docx"
        return_url = SimpleMinioClient().process_word_document("jsj-bucket",description+"故障报告.docx",placeholders,"jsj-bucket",object_name)
        print(return_url)
        return return_url










